﻿using System;
using System.Collections.ObjectModel;
using System.ComponentModel.Composition;
using Caliburn.Micro;
using YiJing.Model;
using YiJing.Properties;
using YiJing.Tasks;

namespace YiJing.ViewModels
{
    [Export(typeof(CoinTossViewModel)), PartCreationPolicy(CreationPolicy.NonShared)]
    public sealed class CoinTossViewModel : Screen, IDialog
    {
        private const int TotalCoins = 3;

        private readonly Random _series = new Random();
        private readonly ObservableCollection<Line> _hexagram = new ObservableCollection<Line>();

        public event EventHandler<DialogResultCompletionEventArgs> Completed;

        public CoinTossViewModel()
        {
            DisplayName = Resources.Caption_GenerateHexagram;
            CoinToss = new CoinSet(TotalCoins);

            _hexagram.CollectionChanged += delegate { OnHexagramChanged(); };
        }

        public CoinSet CoinToss
        {
            get;
            set;
        }

        public object Lines
        {
            get { return _hexagram; }
        }

        public HexagramFigure Result
        {
            get  { return new HexagramFigure(_hexagram); }
        }

        public bool CanAdd
        {
            get { return _hexagram.Count < HexagramFigure.MaxLines; }
        }

        public void Add()
        {
            _hexagram.Insert(0, CoinToss.ToLine());
        }

        public bool CanAddRandom
        {
            get { return CanAdd; }
        }

        public void AddRandom()
        {
            CoinToss.HeadsCount = _series.Next(0, TotalCoins + 1);
            Add();
        }

        public bool CanAddAll
        {
            get { return CanAdd; }
        }

        public void AddAll()
        {
            while (_hexagram.Count < HexagramFigure.MaxLines)
                AddRandom();
        }

        public bool CanRemove
        {
            get { return _hexagram.Count > 0; }
        }

        public void Remove()
        {
            _hexagram.RemoveAt(0);
        }

        public void Clear()
        {
            _hexagram.Clear();
            CoinToss.HeadsCount = 0;
        }

        public bool CanOK
        {
            get { return _hexagram.Count == HexagramFigure.MaxLines; }
        }

        public void OK()
        {
            Completed(this, new DialogResultCompletionEventArgs { DialogResult = true });
        }

        private void OnHexagramChanged()
        {
            NotifyOfPropertyChange(() => CanOK);
            NotifyOfPropertyChange(() => CanAdd);
            NotifyOfPropertyChange(() => CanAddRandom);
            NotifyOfPropertyChange(() => CanAddAll);
            NotifyOfPropertyChange(() => CanRemove);
        }
    }
}
